import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Register from '@/views/register'
import Layout from '@/views/layout'
import Article from '@/views/article.vue'
import Collect from '@/views/collect.vue'
import Like from '@/views/like.vue'
import User from '@/views/user.vue'
import { getToken } from '@/utils/storage'

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  {
    path: '/',
    component: Layout,
    redirect: '/article',
    children: [
      { path: 'article', component: Article },
      { path: 'collect', component: Collect },
      { path: 'like', component: Like },
      { path: 'user', component: User }
    ]
  }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/login', '/register'] // 白名单
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (whiteList.includes(to.path)) {
    // 如果在白名单中
    next() // 直接放行
  } else if (token) {
    // 如果不在，但是手里有token
    next() // 放行
  } else {
    next('/login') // 强制让它去登录
  }
})

export default router
